package com.sgb.kjwl.view.ui.fragment.material;

import android.content.Context;
import android.content.Intent;
import android.os.Bundle;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;

import androidx.annotation.Nullable;
import androidx.databinding.DataBindingUtil;
import androidx.fragment.app.Fragment;

import com.google.android.material.tabs.TabLayout;
import com.sgb.goods.entity.GoodsItemEntity;
import com.sgb.goods.view.activity.inquiry.NewPurchasesActivity;
import com.sgb.kjwl.AppFragment;
import com.sgb.kjwl.R;
import com.sgb.kjwl.databinding.FragmentDemandHallBinding;
import com.sgb.kjwl.di.home.DaggerHomeFragComponent;
import com.sgb.kjwl.di.home.HomeFragModule;
import com.sgb.kjwl.model.entity.supplier3.DictEntity3;
import com.sgb.kjwl.view.ui.fragment.demandHall.DemandHallListFragment2;
import com.sgb.kjwl.view.ui.fragment.home.MaterialHomeFragment1;
import com.sgb.kjwl.view.widget.DemandHallTypePopWindow;
import com.sgb.kjwl.viewmodel.demand.DemandHallFragModel;
import com.sgb.link.event.LeaseEvent;
import com.swgk.core.base.di.AppComponent;
import com.swgk.core.dialog.BasePopWindow;
import com.swgk.core.event.EventConstant;
import com.swgk.core.recyclerview.adapter.FragPagerAdapter;
import com.swgk.core.util.ACAdminDialogUtils;
import com.swgk.core.util.MToast;
import com.swgk.core.view.entity.MenuEntity;

import org.greenrobot.eventbus.EventBus;

import java.util.ArrayList;
import java.util.List;

import javax.inject.Inject;

import static com.swgk.core.util.ACAdminDialogUtils.MK_OURINQUIRYPRICELIST;

/**
 * 首页商品：需求大厅界面fragment 9月10号需求
 */
public class DemandHallFragment extends AppFragment {

    private FragmentDemandHallBinding binding;
    private ArrayList<Fragment> mFragments = new ArrayList<>();

    @Inject
    DemandHallFragModel demandHall;
    private String[] titles;
    private FragPagerAdapter pagerAdapter;
    List<DictEntity3> dictdata;
    private DemandHallTypePopWindow demandHallTypePopWindow;
    private boolean isCreate = false;
    private boolean init = true;
    private boolean isVisible;
    private static int whereFrom = 0;
    private int choiceclass = 0;

    /***
     *
     * @param fromWhere 默认传0，首页商品模块的需求大厅进入传1；
     * @return
     */
    public static DemandHallFragment newInstance(int fromWhere) {
        whereFrom = fromWhere;
        DemandHallFragment fragment = new DemandHallFragment();
        return fragment;
    }

    @Override
    protected void setupFragmentComponent(AppComponent appComponent) {
        DaggerHomeFragComponent.builder()
                .appComponent(appComponent)
                .homeFragModule(new HomeFragModule(this))
                .build()
                .inject(this);
    }

    @Override
    public void setUserVisibleHint(boolean isVisibleToUser) {
        super.setUserVisibleHint(isVisibleToUser);
        isVisible = isVisibleToUser;
        if (!isCreate) {
            return;
        }
        if (isVisibleToUser) {
            if (init) {
                init = false;
                init();
            }
        }
    }

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        EventBus.getDefault().postSticky(this);
        isCreate = true;
    }

    @Nullable
    @Override
    public View onCreateView(LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {
        binding = DataBindingUtil.inflate(inflater, R.layout.fragment_demand_hall, container, false);
        return binding.getRoot();
    }

    @Override
    public void onActivityCreated(@Nullable Bundle savedInstanceState) {
        super.onActivityCreated(savedInstanceState);
        initView();
        if (init && isVisible) {
            init = false;
            init();
        }
    }

    private void initView() {
        binding.editView.setOnClickListener(this);
//      商品类型
        demandHallTypePopWindow = new DemandHallTypePopWindow(getActivity());
        demandHallTypePopWindow.setOnResultClick(new BasePopWindow.OnResultClick() {
            @Override
            public void result(Object key1, Object key2, Object key3) {
//                binding.tablayout.setCurrentTab((int) key2);
                binding.tablayout.postDelayed(new Runnable() {
                    @Override
                    public void run() {
                        binding.tablayout.getTabAt((int) key2).select();
                    }
                }, 100);
            }
        });


        binding.tablayout.addOnTabSelectedListener(new TabLayout.OnTabSelectedListener() {
            @Override
            public void onTabSelected(TabLayout.Tab tab) {
                choiceclass = tab.getPosition();
                setTabLayoutName(tab.getPosition());
                demandHallTypePopWindow.setDefItem(tab.getPosition());
                binding.viewpager.setCurrentItem(choiceclass);
            }

            @Override
            public void onTabUnselected(TabLayout.Tab tab) {

            }

            @Override
            public void onTabReselected(TabLayout.Tab tab) {

            }
        });

        binding.mtabtitle.addOnTabSelectedListener(new TabLayout.OnTabSelectedListener() {
            @Override
            public void onTabSelected(TabLayout.Tab tab) {
                choice_Industry = tab.getPosition();

                if(choice_Industry==0){
                    binding.linClass.setVisibility(View.GONE);
                    List<DictEntity3> listdata = new ArrayList<>();
                    DictEntity3 datas = new DictEntity3();
                    datas.setId("");
                    datas.setName("全部");
                    listdata.add(datas);
                    getDemanHallTabList(listdata);
                }else {
                    binding.linClass.setVisibility(View.VISIBLE);
                    demandHall.getMenuModel(MaterialHomeFragment1.IndustryItemlist.get(choice_Industry).getId()+"");
                }
            }

            @Override
            public void onTabUnselected(TabLayout.Tab tab) {

            }

            @Override
            public void onTabReselected(TabLayout.Tab tab) {

            }
        });
    }

    //获取tab页签名称
    private void setTabLayoutName(int position) {
        if (null != dictdata && dictdata.size() > 0) {
            EventBus.getDefault().postSticky(LeaseEvent.make().setMessageTag(EventConstant.EVENT_SELECT_DEMANDHALL_TAB).setMessageData(dictdata.get(position).getName() + ""));
        }
    }

    @Override
    public void onClick(View v) {
        switch (v.getId()) {
            case R.id.edit_view://材料类型下拉框
                if (null == dictdata || dictdata.size() == 0)
                    return;
                demandHallTypePopWindow.showPopwindow(binding.editView, 0, 0);
                demandHallTypePopWindow.setData(dictdata, choiceclass);
                break;
        }
    }


    private void init() {
//        获取tab材料类型
        if(MaterialHomeFragment1.IndustryItemlist.size()>0){
            showTabIndustryList();
        }else {
            demandHall.getDemandHallList();
        }
    }

    /*
     * 根据接口返回的tab页签数来动态加载对应的fragment页面和viewpager绑定
     * */
    public void getDemanHallTabList(List<DictEntity3> data) {


        if (null != data && data.size() > 0) {

            dictdata = data;
            mFragments = new ArrayList<>();
            int size = data.size();
            titles = new String[size];
            for (int i = 0; i < size; i++) {
                mFragments.add(DemandHallListFragment2.newInstance(data.get(i).getName(), whereFrom));
                titles[i] = data.get(i).getName();
            }
            if(pagerAdapter==null) {
                pagerAdapter = new FragPagerAdapter(getChildFragmentManager(), mFragments);
                binding.viewpager.setAdapter(pagerAdapter);
                binding.viewpager.setOffscreenPageLimit(titles.length - 1);
            }else{
                pagerAdapter.notifyDataSetChanged();
                binding.viewpager.setOffscreenPageLimit(titles.length - 1);
                binding.viewpager.setCurrentItem(0);
            }
            choiceclass = 0;
            binding.tablayout.removeAllTabs();
            for (int i = 0; i < data.size(); i++) {
                binding.tablayout.addTab(binding.tablayout.newTab().setText(data.get(i).getName()), i ==0 );
            }

        } else {
            MToast.showToast(getActivity(), "数据未加载");
        }
    }


    @Override
    public void onDestroy() {
        super.onDestroy();
        EventBus.getDefault().unregister(this);
    }

    public void goLogin(Context context) {
        int type = ACAdminDialogUtils.isPermissionForAsk(MK_OURINQUIRYPRICELIST, true);
        if (type == ACAdminDialogUtils.TYPE_NORMAL) {
            Intent createGood = new Intent(context, NewPurchasesActivity.class);
            createGood.putExtra("GOOD_EDIT", false);
            createGood.putExtra("GOOD_ENTITY", new GoodsItemEntity());
            createGood.putExtra("GOOD_ADD", false);
            context.startActivity(createGood);
        } else {
            ACAdminDialogUtils.showACDialogForGoods(type, context);
        }
    }

    private int choice_Industry = 0;
    public void showTabIndustryList() {


            binding.mtabtitle.setVisibility(View.VISIBLE);

            binding.mtabtitle.removeAllTabs();
            for (int i = 0; i < MaterialHomeFragment1.IndustryItemlist.size(); i++) {

                binding.mtabtitle.addTab(binding.mtabtitle.newTab().setText(MaterialHomeFragment1.IndustryItemlist.get(i).getName()), choice_Industry == i);
            }
            if(choice_Industry==0){
                binding.linClass.setVisibility(View.GONE);
                return;
            }
            binding.mtabtitle.postDelayed(new Runnable() {
                @Override
                public void run() {
                    binding.mtabtitle.getTabAt(choice_Industry).select();
                }
            }, 100);

    }


    public void showPopWindowClassOne(List<MenuEntity> data){
        List<DictEntity3> listdata = new ArrayList<>();
        if(data.size()>0){
            for (MenuEntity datum : data) {
                DictEntity3 datas = new DictEntity3();
                datas.setId(datum.getId());
                datas.setName(datum.getName());
                listdata.add(datas);
            }
        }
        getDemanHallTabList(listdata);
    }

}
